﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;
using System.Collections;

namespace Yuanlin.Business
{
    public class ZiCaiInfoAddControl : YuanlinUserControl
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedTextBox priceValuedTextBox;
        protected ValuedEditor descriptionValuedEditor;
        protected ValuedDropDownList topZiCaiCategoryDropDownList;
        protected ValuedDropDownList secondZiCaiCategoryDropDownList;
        protected RadioButtonList categoryRadioButtonList;//分类
        protected HiddenField specificationHiddenField;
        protected ValuedTextBox registerTrademarkValuedTextBox;
        protected HtmlInputFile attachmentData;
        protected Literal zicaiInfoLiteral;
        protected IButton SaveButton;
        protected IButton BackButton;
        private YuanlinUser user = HttpContext.Current.User as YuanlinUser;
        private int kind = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Kind);
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack && !Page.IsAsync)
            {
                Bind();
            }
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }
        private void Bind()
        {
            zicaiInfoLiteral.Text = ZiCaiInfoControl.TitleStr(kind,tradeType);

            ZiCaiListRequest request = new ZiCaiListRequest();
            request.UpZiCaiId = 0;
            EntityList topCategories = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(request));

            topZiCaiCategoryDropDownList.DataSource = topCategories;
            topZiCaiCategoryDropDownList.DataValueField = "EntityId";
            topZiCaiCategoryDropDownList.DataTextField = "Title";
            topZiCaiCategoryDropDownList.DataBind();
            topZiCaiCategoryDropDownList.SelectedValue = kind.ToString();

            ZiCaiListRequest requestZiCai = new ZiCaiListRequest();
            requestZiCai.UpZiCaiId = kind;
            EntityList defaultCategories = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(requestZiCai));

            ZiCai category = new ZiCai();
            category.Title.Value = "<请选择>";
            category.EntityId.Value = -1;
            defaultCategories.Insert(0, category);

            secondZiCaiCategoryDropDownList.DataSource = defaultCategories;
            secondZiCaiCategoryDropDownList.DataValueField = "EntityId";
            secondZiCaiCategoryDropDownList.DataTextField = "Title";
            secondZiCaiCategoryDropDownList.DataBind();

            //资材规格分类
            ZiCaiGuiGeCategoryListRequest request1 = new ZiCaiGuiGeCategoryListRequest();
            request1.ZiCaiId = kind;
            request1.PageIndex = 0;
            request1.PageSize = 10000;
            EntityList categories = BusinessManager.GetZiCaiGuiGeCategoryList(RequestHelper.BuildGetZiCaiGuiGeCategoryListRequest(request1));
            this.categoryRadioButtonList.DataSource = categories;
            this.categoryRadioButtonList.DataTextField = "Title";
            this.categoryRadioButtonList.DataValueField = "EntityId";
            this.categoryRadioButtonList.DataBind();

        }
        public void BackButton_Click(object sender, EventArgs e)
        {
            RedirectUrl();
        }

        private void RedirectUrl()
        {
            if (kind == 1)//机械
            {
                if (tradeType == "0")//出售
                { 
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMachineChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMachineQiuGouListUrl());
                }
            }
            else if (kind == 2)//设施
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyFacilityChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyFacilityQiuGouListUrl());
                }
            }
            else if (kind == 3)//农资
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyAgriculturalChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyAgriculturalQiuGouListUrl());
                }
            }
            else if (kind == 4)//化肥
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyHuaFeiChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyHuaFeiQiuGouListUrl());
                }
            }
            else if (kind == 5)//饲料
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMashChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMashQiuGouListUrl());
                }
            }
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            ZiCaiInfo ziCaiInfo = new ZiCaiInfo();
            
            ziCaiInfo.Title.Value =  CensorWordManager.CensorWord(this.titleValuedTextBox.Value);
            ziCaiInfo.Body.Value =  CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
            ziCaiInfo.TradeType.Value = tradeType;
            ziCaiInfo.TopCategory.Value = kind;
            ziCaiInfo.SecondCategory.Value = int.Parse(Page.Request.Form[this.secondZiCaiCategoryDropDownList.UniqueID]);
            ziCaiInfo.Kind.Value = kind;
            ziCaiInfo.Price.Value = priceValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(priceValuedTextBox.Text));
            ziCaiInfo.RegisterTrademark.Value = registerTrademarkValuedTextBox.Text.Trim();
            ziCaiInfo.CategoryId.Value = Int32.Parse(categoryRadioButtonList.SelectedValue);
            string topCategoryText = string.Empty;
            string secondCategoryText = string.Empty;
            string thirdCategoryText = string.Empty;

            ZiCai topZiCai = BusinessManager.GetZiCai(ziCaiInfo.TopCategory.Value);
            if (topZiCai != null)
            {
                topCategoryText = topZiCai.Title.Value;
            }
            ZiCai secondZiCai = BusinessManager.GetZiCai(ziCaiInfo.SecondCategory.Value);
            if (secondZiCai != null)
            {
                secondCategoryText = secondZiCai.Title.Value;
            }
            ziCaiInfo.SecondCategoryText.Value = secondCategoryText;
            ziCaiInfo.CategoryInfo.Value = string.Format("{0}/{1}", topCategoryText, secondCategoryText);

            ziCaiInfo.Province.Value = user.Province.Value;
            ziCaiInfo.City.Value = user.City.Value;
            ziCaiInfo.Town.Value = user.Town.Value;
            ziCaiInfo.SmallTown.Value = user.SmallTown.Value;
            ziCaiInfo.CompanyName.Value = user.CompanyName.Value;
            ziCaiInfo.UserId.Value = user.EntityId.Value;
            ziCaiInfo.GreenNum.Value = user.RegisterGreenNumber.Value;;
            ziCaiInfo.CreateDate.Value = DateTime.Now;
            ziCaiInfo.UpdateDate.Value = DateTime.Now;

            List<string> fieldNames = new List<string>();
            List<string> fieldValues = new List<string>();
            List<string> fieldUnits = new List<string>();
            if (specificationHiddenField.Value.Length > 0)
            {
                string[] specifications = specificationHiddenField.Value.Split(';');
                foreach (string item in specifications)
                {
                    fieldNames.Add(item.Split(':')[0]);
                    fieldValues.Add(item.Split(':')[1]);
                    fieldUnits.Add(item.Split(':')[2]);
                }
            }
            ziCaiInfo.GuiGeNames.Value = string.Join("|", fieldNames.ToArray());
            ziCaiInfo.GuiGeValues.Value = string.Join("|", fieldValues.ToArray());
            ziCaiInfo.GuiGeUnits.Value = string.Join("|", fieldUnits.ToArray());

            BusinessManager.CreateZiCaiInfo(ziCaiInfo);

            if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
            {
                ziCaiInfo.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                BusinessManager.UpdateZiCaiInfo(ziCaiInfo);
                SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(ziCaiInfo), attachmentData);
            }

            if (kind == 1)//机械
            {
                if (tradeType == "0")//出售
                {
                    if (string.IsNullOrEmpty(user.CompanyMachineChuShou))
                    {
                        user.CompanyMachineChuShou = "1";
                    }
                    else
                    {
                        user.CompanyMachineChuShou = (Globals.ChangeType<int>(user.CompanyMachineChuShou) + 1).ToString();
                    }
                }
                else if (tradeType == "1")//求购
                {
                    if (string.IsNullOrEmpty(user.CompanyMachineQiuGou))
                    {
                        user.CompanyMachineQiuGou = "1";
                    }
                    else
                    {
                        user.CompanyMachineQiuGou = (Globals.ChangeType<int>(user.CompanyMachineQiuGou) + 1).ToString();
                    }
                }
            }
            else if (kind == 2)//设施
            {
                if (tradeType == "0")//出售
                {
                    if (string.IsNullOrEmpty(user.CompanyFacilityChuShou))
                    {
                        user.CompanyFacilityChuShou = "1";
                    }
                    else
                    {
                        user.CompanyFacilityChuShou = (Globals.ChangeType<int>(user.CompanyFacilityChuShou) + 1).ToString();
                    }
                }
                else if (tradeType == "1")//求购
                {
                    if (string.IsNullOrEmpty(user.CompanyFacilityQiuGou))
                    {
                        user.CompanyFacilityQiuGou = "1";
                    }
                    else
                    {
                        user.CompanyFacilityQiuGou = (Globals.ChangeType<int>(user.CompanyFacilityQiuGou) + 1).ToString();
                    }
                }
            }
            else if (kind == 3)//农资
            {
                if (tradeType == "0")//出售
                {
                    if (string.IsNullOrEmpty(user.CompanyAgriculturalChuShou))
                    {
                        user.CompanyAgriculturalChuShou = "1";
                    }
                    else
                    {
                        user.CompanyAgriculturalChuShou = (Globals.ChangeType<int>(user.CompanyAgriculturalChuShou) + 1).ToString();
                    }
                }
                else if (tradeType == "1")//求购
                {
                    if (string.IsNullOrEmpty(user.CompanyAgriculturalQiuGou))
                    {
                        user.CompanyAgriculturalQiuGou = "1";
                    }
                    else
                    {
                        user.CompanyAgriculturalQiuGou = (Globals.ChangeType<int>(user.CompanyAgriculturalQiuGou) + 1).ToString();
                    }
                }
            }
            else if (kind == 4)//化肥
            {
                if (tradeType == "0")//出售
                {
                    if (string.IsNullOrEmpty(user.CompanyHuaFeiChuShou))
                    {
                        user.CompanyHuaFeiChuShou = "1";
                    }
                    else
                    {
                        user.CompanyHuaFeiChuShou = (Globals.ChangeType<int>(user.CompanyHuaFeiChuShou) + 1).ToString();
                    }
                }
                else if (tradeType == "1")//求购
                {
                    if (string.IsNullOrEmpty(user.CompanyHuaFeiQiuGou))
                    {
                        user.CompanyHuaFeiQiuGou = "1";
                    }
                    else
                    {
                        user.CompanyHuaFeiQiuGou = (Globals.ChangeType<int>(user.CompanyHuaFeiQiuGou) + 1).ToString();
                    }
                }
            }
            else if (kind == 5)//饲料
            {
                if (tradeType == "0")//出售
                {
                    if (string.IsNullOrEmpty(user.CompanyMashChuShou))
                    {
                        user.CompanyMashChuShou = "1";
                    }
                    else
                    {
                        user.CompanyMashChuShou = (Globals.ChangeType<int>(user.CompanyMashChuShou) + 1).ToString();
                    }
                }
                else if (tradeType == "1")//求购
                {
                    if (string.IsNullOrEmpty(user.CompanyMashQiuGou))
                    {
                        user.CompanyMashQiuGou = "1";
                    }
                    else
                    {
                        user.CompanyMashQiuGou = (Globals.ChangeType<int>(user.CompanyMashQiuGou) + 1).ToString();
                    }
                }
            }
           UserManager.UpdateUser(user);

            RedirectUrl();
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }
            ZiCaiListRequest request = new ZiCaiListRequest();
            request.UpZiCaiId = parentCategoryID;
            EntityList categories = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(request));
            if (categories != null && categories.Count > 0)
            {
                string categoryFormat = "{0}:{1}";
                string categoryString = string.Empty;
                foreach (ZiCai category in categories)
                {
                    categoryString += ";" + string.Format(categoryFormat, category.EntityId.Value.ToString(), category.Title.Value);
                }
                if (categoryString.Length > 0)
                {
                    categoryString = categoryString.Substring(1);
                }
                return categoryString;
            }

            return string.Empty;
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string ParentCategorySelectedChanged(string selectedValue)
        {
            if (string.IsNullOrEmpty(selectedValue))
            {
                return "";
            }

            return BindGuiGes(int.Parse(selectedValue));
        }
        private string BindGuiGes(int categoryID)
        {
            string returnValue = string.Empty;
            if (categoryID < 0)
            {
                return returnValue;
            }

            //绑定规格
            ZiCaiGuiGeListRequest request = new ZiCaiGuiGeListRequest();
            request.CategoryId = categoryID;
            EntityList ziCaiGuiGes = BusinessManager.GetZiCaiGuiGeList(RequestHelper.BuildGetZiCaiGuiGeListRequest(request));
            if (ziCaiGuiGes.Count > 0)
            {
                string format = "{0}:{1}";
                string str = string.Empty;
                foreach (ZiCaiGuiGe item in ziCaiGuiGes)
                {
                    str += ";" + string.Format(format, item.Title.Value, item.Unit.Value);
                }
                if (str.Length > 0)
                {
                    str = str.Substring(1);
                }
                returnValue = str;
            }

            return returnValue;
        }
    }
}